<template>
  <div class="community">
    <!-- 顶部用户信息 -->
    <user-info ref="userinfoRef" />

    <div class="center-wrap">
      <!-- 团购介绍 -->
      <introduce ref="introduceRef" />

      <!-- 团购商品 -->
      <products ref="productsRef" />

      <!-- 团购设置 -->
      <set-info ref="setInfoRef" />
    </div>

    <!-- 操作按钮：保存、发布 -->
    <div class="action">
      <button class="action-btn" @click="handlePublish">
        {{ publishTextCpt }}
      </button>
    </div>
    <i v-if="isIOS" class="toolman"></i>

    <tip-dialog ref="tipDialogRef" @confirm="handleDialogConfirm">
      <template #title>
        <div class="dialog-title">温馨提示</div>
      </template>

      <template #default>
        <div class="dialog-content">
          <div class="text-line first-line">
            为维护良好团购环境，微团购用户不得发布包含枪支弹药或危化品等违禁商品的团购，如有违规微团购有权采取封禁等违规处理措施，并保留追究团长法律责任的权利。
          </div>
          <div class="text-line second-line" @click="goToPrivacy">
            请审慎阅读并理解<span class="link"
              >《微团购禁发商品和信息管理规范》。</span
            >
          </div>
        </div>
      </template>

      <template #cancel>不同意</template>
      <template #confirm>同意</template>
    </tip-dialog>
  </div>
</template>

<script lang="ts" setup>
import UserInfo from "../components/userinfo/userinfo.vue";
import Introduce from "../components/introduce/introduce.vue";
import Products from "../components/products/products.vue";
import SetInfo from "../components/setinfo/setinfo.vue";
import TipDialog from "@/components/Dialog/index.vue";
import _ from "lodash";
import { useRouter, useRoute } from "vue-router";
import { Toast } from "@nutui/nutui";
import { publishApi } from "@/api/addstart";
import { ref, nextTick, onActivated, computed } from "vue";
import { judgeClient, timestampToTime } from "@/utils/utils";
import { isRes } from "@/utils/pub-use";
const { isIOS } = judgeClient();

// ------ router
const router = useRouter();
const route = useRoute();

// ------ data
const userinfoRef = ref<InstanceType<typeof UserInfo>>();
const introduceRef = ref<InstanceType<typeof Introduce>>();
const productsRef = ref<InstanceType<typeof Products>>();
const setInfoRef = ref<InstanceType<typeof SetInfo>>();
const tipDialogRef = ref<InstanceType<typeof TipDialog>>();
const finalData = ref<any>(null);
const groupbuy_id = ref<any>(null);

// ------ computed
const publishTextCpt = computed(() => {
  return route.query.groupbuy_id ? "保存" : "发布";
});

// - methods
const goToPrivacy = () => {
  router.push("/privacy");
};
// 按钮：触发数据校验(团购介绍必填、团购商品的必填项必填、团购设置必填)，通过则打开确认弹窗
const handlePublish = async () => {
  let isAllow = true; // 条件满足记号，为true时才可发布

  // 1.团购介绍判断(条件：全部不能为空)
  const introduceData = introduceRef.value?.handleCommit() as any;

  if (introduceData) {
    if (!introduceData.title) isAllow = false;

    if (introduceData.content && introduceData.content.length > 0) {
      introduceData.content.map((it: any) => {
        if (!it.text && !it.smallImages[0] && !it.bigImage[0]) isAllow = false;
      });
    } else {
      isAllow = false;
    }
  } else {
    isAllow = false;
  }
  if (!isAllow) {
    Toast.warn("请检查“团购介绍”信息");
    return;
  }

  // 2.团购商品判断(条件：必填项不能为空)
  const productData: any[] = (await productsRef.value?.handleCommit()) as any[];
  if (productData && productData.length > 0) {
    for (const item of productData) {
      if (!item || !item.name || !item.price) {
        isAllow = false;
        break;
      }
    }
  } else {
    isAllow = false;
  }
  if (!isAllow) {
    Toast.warn("请检查“团购商品”信息");
    return;
  }

  // 3.团购设置判断(条件：全部不能为空)
  const setInfoData = setInfoRef.value?.handleCommit() as any;
  if (setInfoData) {
    for (const key in setInfoData) {
      if (
        key !== "isChecked" &&
        (!setInfoData[key] || setInfoData[key].length <= 0)
      ) {
        isAllow = false;
        break;
      }
    }
  } else {
    isAllow = false;
  }
  if (!isAllow) {
    Toast.warn("请检查“团购设置”");
    return;
  }
  const nowTime = timestampToTime(new Date().valueOf())
    if (
      setInfoData.startDate >= setInfoData.endDate ||
      setInfoData.startDate < nowTime ||
      setInfoData.endDate < nowTime
    ) {
      isAllow = false
      Toast.warn("请检查开始或结束时间")
      return
    }

  // 发布
  if (isAllow) {
    finalData.value = {
      introduceData,
      productData,
      setInfoData,
    };

    tipDialogRef.value?.openDialog();

    // 清空本地缓存的数据
    // setTimeout(() => {
    //   removeLocalCache(productData)
    // }, 500)
  }
};
// 弹窗：触发确认发布
const handleDialogConfirm = () => {
  publishRequest();
  // if (route.query.groupbuy_id) {
  //   saveRequest()
  // } else {
  //   publishRequest()
  // }
};

// ------ request
// 接口：发布新建的团购信息
async function publishRequest() {
  const result = handlerTool(); // 字段名、格式不一致，这里统一处理一下
  // console.log('-整理前的最终数据', finalData.value)
  // console.log('-整理后的最终数据', result)

  const res = await publishApi(result);
  if (isRes(res)) {
    nextTick(() => {
      introduceRef.value?.resetData();
      productsRef.value?.resetData();
      setInfoRef.value?.resetData();
    });
    finalData.value.productData?.forEach((item: any) => {
      window.localStorage.removeItem(`productDesc-${item.id}`); // 描述item
      window.localStorage.removeItem(`specData1-${item.id}`); // 规格item
      window.localStorage.removeItem(`specData2-${item.id}`); // 规格item
    });
    finalData.value = null;
    Toast.text("发布成功");
    router.push("/home");
  } else {
    Toast.fail("发布失败");
  }
}
// 接口：保存编辑的团购信息
async function saveRequest() {
  const result = handlerTool(); // 字段名、格式不一致，这里统一处理一下
  console.log("保存成功", result);
}

// ------ tool
// 工具函数：用于处理接口数据格式
function handlerTool() {
  const { introduceData, productData, setInfoData } = _.cloneDeep(
    finalData.value
  );

  // 1.buy_type 团购类型 (1是普通团购，2是小区团购)
  const buy_type =
    window.localStorage.getItem("nowAddType") == "ordinary" ? 1 : 2;

  // 2.title  团购介绍的标题
  const title = introduceData.title;

  // 3.logistics_type 物流方式 (1.快递 2.自提 3.快递+自提)
  let logistics_type = 1;
  let self_priming_ids: any[] = [];
  if (setInfoData.logistics.delivery && setInfoData.logistics.village) {
    logistics_type = 3;
    self_priming_ids = setInfoData.logistics.villageIdArr;
  } else if (setInfoData.logistics.delivery) {
    logistics_type = 1;
  } else if (setInfoData.logistics.village) {
    logistics_type = 2;
    self_priming_ids = setInfoData.logistics.villageIdArr;
  }

  // 4.start_time 开始时间 end_time 结束时间
  const start_time = setInfoData.startDate;
  const end_time = setInfoData.endDate;

  // 5.is_allowed_refund 是否允许退款 (1.允许 2.不允许)
  const is_allowed_refund = setInfoData.isChecked ? 1 : 0;

  // 6.image_text_vos 团购介绍 (1.是大图 2.是小图数组 3.是文本 4.是视频)
  const image_text_vos: any[] = [];
  for (const item of introduceData.content) {
    let it: any = { type: item.type, content: item.text };

    switch (item.type) {
      case 1:
        it = { type: item.type, content: item.bigImage[0] };
        break;
      case 2:
        it = { type: item.type, content_list: [...item.smallImages] };
        break;
      case 3:
        it = { type: item.type, content: item.text };
        break;
      case 4:
        it = { type: item.type, content: item.video, cover: item.cover };
        break;
      default:
        break;
    }

    image_text_vos.push(it);
  }

  // 7.goods_list 团购商品
  const goods_list: any[] = [];
  for (const item of productData) {
    let it: any = {};

    // 拿spec_list数据
    const spec_list: any[] = [];
    for (const it of item.specData.specData2) {
      spec_list.push({
        spec_combination_id: it.id,
        price: it.price,
        real_price: it.basePrice,
        stock: it.stok ? it.stok : it.stok == 0 ? 0 : -1,
        image: it.img,
      });
    }

    it = {
      goods_name: item.name,
      description: item.desc,
      image_list: item.imageList,
      // price: item.price,
      line_price: item.crossedPrice,
      // real_price: item.costPrice,
      spec_list,
    };

    goods_list.push(it);
  }

  const result = {
    buy_type,
    title,
    logistics_type,
    self_priming_ids,
    start_time,
    end_time,
    is_allowed_refund,
    image_text_vos,
    goods_list,
    intro: "", // 字段废弃，传空即可
  };

  return result;
}

// ------ lifecycle
onActivated(() => {
  window.localStorage.setItem("nowAddType", "community");

  // if (route.query.groupbuy_id) {
  //   groupbuy_id.value = route.query.groupbuy_id

  //   let obj = {
  //     buy_type: 1,
  //     title: '团购介绍-标题',
  //     logistics_type: 1,
  //     self_priming_ids: [],
  //     start_time: '2023-01-01 00:00',
  //     end_time: '2023-12-19 00:00',
  //     is_allowed_refund: 1,
  //     image_text_vos: [
  //       {
  //         type: 3,
  //         content: '团购介绍-文字'
  //       },
  //       {
  //         type: 1,
  //         content: '20230418150515_LNlNW.jpeg'
  //       },
  //       {
  //         type: 2,
  //         content_list: ['20230418150523_91Ows.jpg', '20230418151533_ugPBm.jpeg']
  //       },
  //       {
  //         type: 3,
  //         content: '团购介绍-文字2'
  //       }
  //     ],
  //     goods_list: [
  //       {
  //         goods_name: '商品名称',
  //         description: '商品描述',
  //         image_list: ['20230418151617_s95k8.jpg'],
  //         line_price: '5',
  //         spec_list: [
  //           {
  //             spec_combination_id: '12',
  //             price: '2',
  //             real_price: '1',
  //             stock: '5',
  //             image: '20230418151709_xu0Ph.jpeg'
  //           },
  //           {
  //             spec_combination_id: '13',
  //             price: '2',
  //             real_price: '1',
  //             stock: '5',
  //             image: '20230418151715_YoWo7.jpg'
  //           },
  //           {
  //             spec_combination_id: '14',
  //             price: '2',
  //             real_price: '1',
  //             stock: '5',
  //             image: ''
  //           },
  //           {
  //             spec_combination_id: '15',
  //             price: '2',
  //             real_price: '1',
  //             stock: '5',
  //             image: ''
  //           }
  //         ]
  //       }
  //     ],
  //     intro: ''
  //   }

  //   window.localStorage.setItem('editItemData', JSON.stringify(obj))
  // } else {
  //   groupbuy_id.value = null
  //   window.localStorage.removeItem('editItemData')
  // }
});
</script>

<style lang="scss" scoped>
.community {
  position: static;
  // height: 100vh;
  // overflow: auto;
  background: #f7f8f9;

  .center-wrap {
    padding: 0 20px;
  }

  .action {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 112px;
    background: #ffffff;
    margin-top: 115px;

    .action-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 305px;
      height: 90px;
      border: none;
      border-radius: 45px;
      font-size: 30px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #ffffff;
    }
    // .action-btn:first-of-type {
    //   border: 1px solid #40ae36;
    //   background: #ffffff;
    //   color: #40ae36;
    // }
    .action-btn:last-of-type {
      background: linear-gradient(90deg, #3ebd33 0%, #9fdf4f 100%);
      margin-left: 20px;
    }
  }

  .toolman {
    display: block;
    width: 100%;
    height: 68px;
    background: #ffffff;
  }

  .dialog-title {
    font-size: 36px;
    font-family: PingFang-SC-Medium, PingFang-SC;
    font-weight: 500;
    color: #000000;
    line-height: 50px;
    margin: 36px 0 30px 0;
  }
  .dialog-content {
    box-sizing: border-box;
    padding: 0 50px;
    margin-bottom: 61px;

    .text-line {
      font-size: 30px;
      font-family: PingFang-SC-Regular, PingFang-SC;
      font-weight: 400;
      color: #000000;
      line-height: 42px;
      text-align: left;
    }

    .first-line {
    }
    .second-line {
      margin-top: 40px;

      .link {
        color: #40ae36;
      }
    }
  }
}
</style>
